package xq.gwt.ui.widgets.property;

import java.util.LinkedHashMap;

import xq.gwt.mvc.controller.TextPropertyController;
import xq.gwt.mvc.model.ListItem;
import xq.gwt.mvc.model.PropertyModel;
import xq.gwt.mvc.view.TextPropertyView;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;

public class SelectItemPropertyPresenter extends FormItemPropertyPresenter implements TextPropertyView{
	
	protected SelectItem selectItem;	
	protected TextPropertyController controller;	

    public SelectItemPropertyPresenter(SelectItem selectItem){        
    	this.selectItem = selectItem;
    	formItem = this.selectItem;
        init();
        
    }
    
    public SelectItemPropertyPresenter(){  	
    	
    	this.selectItem = new SelectItem();    	
    	formItem = selectItem;
    	init();
    }

	protected void init() {		
		selectItem.addChangedHandler(new ChangedHandler() {
			@Override
			public void onChanged(ChangedEvent event) {
				notifyViewChangedListeners();

			}
		});		
		
		controller = new TextPropertyController(this);
		super.controller = controller;
	}
    
    public void setText(String text) {
        selectItem.setValue(text);
    	       
    }

    public String getText() {
        return selectItem.getValueAsString();    	
    }
    
    public void setModel(PropertyModel model){    	
    	controller.setPropertyModel(model);
    	ListItem[] items = model.getValueItems(); 
    	if (items != null){    		
    		LinkedHashMap<String, String> listItemMap = new LinkedHashMap<String, String>();
    		for (int i = 0; i < items.length; i++) {
				listItemMap.put(items[i].value, items[i].caption);
			}
    		selectItem.setValueMap(listItemMap);
    		selectItem.setSortField(1);
    	}
    		
    }
        
    public SelectItem getSelectItem() {		
    	return selectItem;
	}    
}
